package edu.njust.underwater.exception;

import edu.njust.underwater.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import static edu.njust.underwater.constance.CustomConstance.KEY_NAME;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final String ERROR_VIEW = "error/error";

    @ExceptionHandler(RuntimeException.class)
    public String runtimeExceptionHandler(RuntimeException e) {
        log.error("出错了：{}", e.getMessage());
        return "error/error";
    }


    @ExceptionHandler(ViewException.class)
    public ModelAndView runtimeExceptionHandler(ViewException e) {
        log.error("出错了：{}", e.getMessage());

        ModelAndView modelAndView = new ModelAndView(ERROR_VIEW);
        modelAndView.addObject(KEY_NAME, Result.fail(e.getMessage()));

        return modelAndView;
    }

    @ResponseBody
    @ExceptionHandler(ResponseException.class)
    public Result runtimeExceptionHandler(ResponseException e) {
        log.error("出错了：{}", e.getMessage());

        return Result.fail(e.getMessage());
    }

}
